package com.google.wave.poppy.mail;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

class FetchMail
{
	private static final Logger LOG = Logger.getLogger(FetchMail.class.getName());
	private static final String FETCH_URL = "http://syncstr.com/readwave.php";

	private static void logAsSevere(String message) {
		LOG.log(Level.SEVERE, message);
	}
	
	static List<Message> fetchEmail()
	{
		logAsSevere("Starting to fetch emails");
		
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder;
		Document doc = null;
		InputStream in = null;
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			in = new URL(FETCH_URL).openConnection().getInputStream();
			doc = docBuilder.parse(in);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

		if (doc == null)
			return Collections.EMPTY_LIST;
		
		List<Message> messages = new ArrayList<Message>();
		NodeList nodes_i = doc.getDocumentElement().getChildNodes();
		for (int i = 0; i < nodes_i.getLength(); i++) {
			Node node_i = nodes_i.item(i);
			if (node_i.getNodeType() == Node.ELEMENT_NODE
					&& ((Element) node_i).getTagName().equals("message")) {
						messages.add(parseMessage((Element) node_i));
			}
		}
		
		logAsSevere("Starting to fetch emails");
		return messages;
	}
	
	private static Message parseMessage(Node node)
	{
		Message message = new Message();
		NodeList nodeList = node.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node nodeEle = nodeList.item(i);
			if (nodeEle.getNodeType() == Node.ELEMENT_NODE) {
				Element ele = (Element) nodeEle;
				String tag = ele.getTagName();
				String value = ele.getFirstChild() != null ? ele.getFirstChild().getNodeValue() : null;
				if ("from".equals(tag)) {
					message.setSender(value);
				} else if ("to".equals(tag)) {
					message.setRecipient(value);
				} else if ("waveid".equals(tag)) {
					message.setWaveID(value);
				} else if ("subject".equals(tag)) {
					message.setSubject(value);
				} else if ("body".equals(tag)) {
					message.setBody(value);
				} else {
					System.err.println("Unknown XML tag in message: " + tag);
				}
			}
		}
		return message;
	}
	
	private static String getFirstChildNodeValue(Element element)
	{
		return element.getFirstChild() != null ? element.getFirstChild().getNodeValue() : null;
	}
}
